package com.umeox.watch.moto.launcher.fragment;

import static android.content.Context.POWER_SERVICE;
import static com.umeox.moto.common.log.Logger.getTime;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.FileUtils;
import com.umeox.moto.watch.themes.app.ThemeFragment;
import com.umeox.moto.watch.themes.widget.TextView;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.event.CustomWallpaperChangedEvent;
import com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent;
import com.umeox.watch.moto.launcher.event.NotificationManagerEvent;
import com.umeox.watch.moto.launcher.event.ScrollToPagerEvent;
import com.umeox.watch.moto.launcher.event.WatchFaceChangeEvent;
import com.umeox.watch.moto.launcher.ui.WatchFaceActivity;
import com.umeox.watch.moto.launcher.ui.widget.AnalogClockView;
import com.umeox.watch.moto.launcher.ui.widget.NumberClockView;
import com.umeox.watch.moto.launcher.widget.PrayerTimeView;
import com.umeox.watch.moto.pedometer.base.QuranChallenge;
import com.umeox.watch.moto.pedometer.base.TodayChallenge;
import com.umeox.watch.moto.pedometer.data.PedometerContract;
import com.umeox.watch.moto.pedometer.data.PedometerPresenter;
import com.umeox.watch.moto.pedometer.util.CacheImpl;
import com.umeox.watch.moto.pedometer.util.ICache;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/**
 * Created by Rambo 2019-07-04
 * Describe:
 */
public class HomeFragment extends ThemeFragment implements View.OnLongClickListener, View.OnClickListener, PedometerContract.View {
    public static final String STATE_NTF_COUNT = "state_ntf_count";

    public static final long INTERVAL_STEPS_UPLOAD = TimeUnit.SECONDS.toMillis(30);
    private static final int UPLOAD_STEP = 0x1001;
    private ImageView mWallpaperIv;
    private RelativeLayout mWatchFaceContainer;
    private static HomeFragment INSTANCE;
    private int mNtfCount;
    private View mNewNotificationView;

    private TextView mStepCountTv;

    private PedometerContract.Presenter mPresenter;

    private long mTime;

    private PrayerTimeView mPrayerTimeView;

    private View mWatchFaceView;
    private int currentIconIndex;


    public HomeFragment() {
        INSTANCE = this;
        mPresenter = new PedometerPresenter(this);
    }

    public static HomeFragment getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new HomeFragment();
        }
        return INSTANCE;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
        currentIconIndex = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_base;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mWallpaperIv = view.findViewById(R.id.iv_wallpaper);
        mNewNotificationView = view.findViewById(R.id.rl_new_notification);
        mNewNotificationView.setOnClickListener(this);
        view.findViewById(R.id.rl_root).setOnLongClickListener(this);

        mWatchFaceContainer = view.findViewById(R.id.fl_container_watchFace);
        mStepCountTv = view.findViewById(R.id.tv_step_count);
        mPrayerTimeView = view.findViewById(R.id.view_pt);
        setWallpaper();
        mPresenter.onCreate();
//        mPresenter.getStepInfo();
        mTime = getTime(0);
        mPresenter.uploadSteps(0);
        saveSteps();

    }

    public void saveSteps() {
        mPresenter.saveSteps();
        mHandler.postDelayed(this::saveSteps, TimeUnit.SECONDS.toMillis(30));
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null) {
            Logger.d(TAG, "onResume: ");
            mPresenter.start();
        }
        if (mPrayerTimeView != null) {
            Logger.e("currentIconIndex=" + currentIconIndex);
            if(DataProvider.getWallpaper() > 4){
                mPrayerTimeView.onResume(false);
            }else{
                mPrayerTimeView.onResume(currentIconIndex == 0);
            }
        }
    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_NTF_COUNT, mNtfCount);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle state) {
        super.onViewStateRestored(state);
        if (state == null) {
            return;
        }
        final int count = state.getInt(STATE_NTF_COUNT);
        onNotificationManagerEvent(new NotificationManagerEvent(count));
    }

    private void setWallpaper() {
        //首先获取自定义的壁纸路径
        String customWallpaper = DataProvider.getCustomWallpaper();
        if (TextUtils.isEmpty(customWallpaper)) {
            int wallpaperIndex = DataProvider.getWallpaper();
            setupWatchFaceLayout(wallpaperIndex);
        } else {
            if (FileUtils.isFileExists(customWallpaper)) {
                //mWallpaperIv.setImageDrawable(new BitmapDrawable(getResources(), customWallpaper));
                Glide.with(mContext).load(customWallpaper).override(240).centerCrop().into(mWallpaperIv);
            } else {
                mWallpaperIv.setImageResource(R.drawable.wallpaper_0);
            }
            setDial();
        }
    }

    private void setDial() {
        mWatchFaceContainer.removeAllViews();
        int wallpaper = DataProvider.getWallpaper();
        Logger.e("setDial,currentIconIndex=" + currentIconIndex);
        if (wallpaper > 4) {
            mPrayerTimeView.setVisibility(View.GONE);
        } else {
            mPrayerTimeView.setVisibility(currentIconIndex == 0 ? View.VISIBLE : View.GONE);
        }
        switch (wallpaper) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 7:
            case 8:
                mWatchFaceView = new NumberClockView(mContext);
                break;
            case 5:
            case 6:
                mWatchFaceView = new AnalogClockView(mContext);
                break;
        }
        mWatchFaceContainer.addView(mWatchFaceView);
    }

    private void setupWatchFaceLayout(int wallpaper) {
        final String[] themeIcons = getResources().getStringArray(R.array.wallpaper_icon);
        final int drawableId = getDrawableId(themeIcons[wallpaper]);
        mWallpaperIv.setImageResource(drawableId);
        setDial();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        if (mPresenter != null) {
            mPresenter.stop(mContext);
        }

        if (mPrayerTimeView != null) {
            mPrayerTimeView.onPause();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceStatusChangedEvent(DeviceStatusChangedEvent event) {

    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onWatchFaceChangeEvent(WatchFaceChangeEvent event) {
        final int position = event.mPosition;
        currentIconIndex = CacheImpl.getInstance().get(ICache.KEY_WATCH_FACE_ICON_INDEX, 0);
        Logger.e("position:" + position + ",currentIconIndex=" + currentIconIndex);
        setupWatchFaceLayout(position);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onCustomWallpaperChangedEvent(CustomWallpaperChangedEvent event) {
        setWallpaper();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotificationManagerEvent(NotificationManagerEvent event) {
        mNtfCount = event.count;
        if (mNtfCount > 0) {
            //亮屏操作
            PowerManager pm = (PowerManager) mContext.getSystemService(POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock(
                    PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,
                    "My:Tag"
            );
            wakeLock.acquire(5000);
            wakeLock.release();
        }
        mNewNotificationView.setVisibility(mNtfCount == 0 ? View.GONE : View.VISIBLE);

    }

    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new ScrollToPagerEvent(2));
    }

    private int getDrawableId(String name) {
        return getResources().getIdentifier(name, "drawable", mContext.getPackageName());
    }

    @Override
    public boolean onLongClick(View v) {
        Vibrator mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
        if (mVibrator != null) {
            mVibrator.vibrate(200);
        }
        mContext.startActivity(new Intent(mContext, WatchFaceActivity.class));
        return true;
    }

    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == UPLOAD_STEP) {
                mPresenter.uploadSteps(0);
            }
            return false;
        }
    });

    @Override
    public void onStepCountChange(int stepCounts) {
        mStepCountTv.setText(String.valueOf(stepCounts));
        if (getTime(mTime) >= INTERVAL_STEPS_UPLOAD) {
            Logger.e("=======STEPS_UPLOAD======todayStepCount=" + stepCounts);
            mHandler.removeMessages(UPLOAD_STEP);
            mTime = getTime(0);
            mPresenter.uploadSteps(stepCounts);
            mHandler.sendEmptyMessageDelayed(UPLOAD_STEP, 10 * 1000);
        }
    }

    @Override
    public void onStepInfoChange(int stepTarget) {

    }

    @Override
    public void onHolderInfoChange() {

    }

    @Override
    public void onDistanceUnitChange() {

    }

    @Override
    public void onSportChallengeChange(CopyOnWriteArrayList<TodayChallenge> todayChallenges) {

    }

    @Override
    public void onQuranChallengeChange(CopyOnWriteArrayList<QuranChallenge> quranChallenges) {

    }
}
